<template>
  <a-button @click="handAdd" type="primary" style="margin: 10px">添加</a-button>

  <a-table :columns="columns" :data="tableData">
    <template #action="{ record }">
      <a-button @click="handEdit(record)" style="margin: 0 5px">修改</a-button>
      <a-popconfirm content="确定删除吗？" ok-text="删除" cancel-text="取消" @ok="confirm(record)"
                        @cancel="cancel">
                        <a-button style="margin: 0 5px">删除</a-button>
                    </a-popconfirm>
    </template>
  </a-table>
  <action ref="actionRef" @ok="handQuery" />
</template>
<script setup>
import { Message } from '@arco-design/web-vue'
import { ref, reactive, toRefs, onMounted,toRaw } from 'vue'
import { api } from '~/util/ajax'
import action from './action.vue'
const columns = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
  },
  {
    title: '数量',
    dataIndex: 'number',
    key: 'number',
  },
  {
    title: '操作',
    slotName: 'action',
  },
]
//调用子组件方法
let actionRef = ref()
//列表数据
const data = reactive({
  tableData: [
    {
      id: 1,
      name: '洋葱',
      price: 2.5,
      number: 10,
    },
  ],
  loading: false,
})
let { tableData, loading } = toRefs(data)
// 获取所有数据
onMounted(() => {
  handQuery()
  console.log(actionRef.value,50);
})
//获取所有数据
const handQuery = () => {
  data.loading = true
  api
    .get('/query')
    .then((res) => {
      if (res.result) {
        data.tableData = res.data
      } else {
        data.tableData = []
      }
      loading = false
    })
    .catch((err) => {
      data.tableData = []
      loading = false
    })
}



//添加按钮，触发子组件的add方法
const handAdd = () => {
  console.log(actionRef.value);
  actionRef.value.add()
}
// 修改按钮，触发子组件的修改方法
const handEdit = (row) => {
  actionRef.value.edit(row)
}

   //删除
   const confirm = (e) => {
     console.log(e,99);
        //toRaw 对原生数据修改，不改变原数据,不是响应式
        let _data = { ...toRaw(e) }
        console.log(_data);
        api.delete(`/delete/${_data.id}`).then((res) => {
            if (res.result) {
              Message.success('删除成功')
                handQuery()
            }
        })
    }

    //取消删除
    const cancel = (e) => {
      Message.error('删除取消')
    }




</script>

<style scoped>
a {
  color: #42b983;
}
</style>
